package com.google.code.basic.oop;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;

public class AlarmServiceImpl implements AlarmService {

	private static final Logger logger = Logger.getLogger(AlarmServiceImpl.class);

	private String localAlarmFileName;
	private String LocalAlarmDirName;


	public String getLocalAlarmFileName() {
		return localAlarmFileName;
	}

	public void setLocalAlarmFileName(String localAlarmFileName) {
		this.localAlarmFileName = localAlarmFileName;
	}

	public String getLocalAlarmDirName() {
		return LocalAlarmDirName;
	}

	public void setLocalAlarmDirName(String LocalAlarmDirName) {
		this.LocalAlarmDirName = LocalAlarmDirName;
	}


	public List<Alarm> generateRandomAlarms(int numberOfAlarms) {
		if(numberOfAlarms < 0) { throw new AlarmRangeException("numberOfAlarms should be >= 0");}
		AlarmGenerator alarmGenerator = new AlarmGenerator();
		List<Alarm> result = alarmGenerator.generateAlams(numberOfAlarms);
		return result;
	}


	public List<Alarm> getAlarms(String networkElementName) {
		List<Alarm> result = new ArrayList<Alarm>();
		File f = new File(this.getLocalAlarmDirName() + "\\" + networkElementName);
		File[] listOfFiles = f.listFiles();
		List<String> filesToFetch = new ArrayList<String>();
		if (listOfFiles != null) {
				filesToFetch = getListofFilesToFetch(listOfFiles,this.getLocalAlarmFileName());
				result = fetchAlarmsFromFile(filesToFetch, networkElementName);
		}
		return result;
	}

	private List<Alarm> fetchAlarmsFromFile(List<String> filesList,	String networkElementName) {
		List<Alarm> result = new ArrayList<Alarm>();
		AlarmParser alarmParser = new AlarmParser();
		String fullPathToFile = this.getLocalAlarmDirName() + "\\"	+ networkElementName + "\\";
		for (String fileName: filesList) {
			logger.debug(LoggerFormatter.format(1, LoggerFormatter.Level.DEBUG,
					"Retrieve to Alarms From File(to alarmParser Object): "
							+ fullPathToFile + fileName));
			result.addAll(alarmParser.retrieveAlarmsFromFile(fullPathToFile	+ fileName, networkElementName));
		}
		return result;
	}

	private List<String> getListofFilesToFetch(File[] listOfFiles, String regex) {
		List<String> result = new LinkedList<String>();
		for(File file : listOfFiles) {
			if ((file.isFile()) && (file.getName().matches(regex))) {
				result.add(file.getName());
			}
		}
		return result;
	}



}
